package cn.jcby.app.lebu.service;

import cn.jcby.app.config.QiNiuConfig;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: lihaotian
 * @since: 2023/12/8 11:43
 * @description
 **/
@Service
@Slf4j
public class QiNiuService {

    @Autowired
    private QiNiuConfig qiNiuConfig;
    public List<String> uploadFiles(MultipartFile[] files,String path) {
        List<String> retList = new ArrayList<>() ;
        Configuration cfg = new Configuration(Zone.zone1());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        String token = auth.uploadToken(qiNiuConfig.getBucketName());
        for (MultipartFile file : files) {
            try {
                String ext = "" ;
                String originalFilename = file.getOriginalFilename();
                if (StringUtils.isNotBlank(originalFilename)&&originalFilename.indexOf(".")>-1) {
                    ext = originalFilename.substring(originalFilename.lastIndexOf(".")-1) ;
                }
                Response response = uploadManager.put(file.getBytes(), path+"/"+ UUID.randomUUID().toString()+ext, token);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //System.out.println(putRet.key);
                //System.out.println(putRet.hash);
                retList.add(putRet.key) ;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return retList ;
    }
}
